import { defineStore } from 'pinia'
import { updateCartInfo, getCartList } from '@/api'
import { ref } from 'vue'
const useCart = defineStore('cart', () => {
    const cart = ref([])
    const loadCartp = async() =>{
        delAll()
        cart.value=await getCartList()
    }
    const addInfoToCart = goods => {
        const item = cart.value.find(item => goods.id == item.id)
        if (item) {
            item.num += goods.num
        } else {
            cart.value.push(goods)
        }
    }
    const removeCart = id => {
        cart.value.forEach((item, index) => {
            if (item.id == id) {
                cart.value.splice(index, 1)
            }
        })
    }
    const updateCart = () =>{
        cart.value.forEach(item=>{
            updateCartInfo({ goods_id:item.goods_id, num:item.num })
        })
    }
    const cartCount = () => {
        let sum = 0
        cart.value.forEach(item => {
            sum += item.num
        })
        return sum || undefined
    }
    const cartCheckedCount = () =>{
        let sum = 0
        cart.value.forEach(item=>{
            if(item.checked){
                sum+= item.num
            }
        } )
        return sum || undefined
    }
    const delAll = () =>{
        cart.value=[]
    }
    const cartValue = () =>{
        return cart.value
    }
    const cartCheckedChange = (id) =>{
        console.log(id);
        console.log(cart);
        cart.value.forEach(item =>{
            console.log(item.id,id);
            if(item.goods_id === id){
                item.checked= true
            }else{
                item.checked= false
            }
        })
    }
    return { cart, removeCart, cartCount, addInfoToCart, updateCart, loadCartp, delAll, cartValue, cartCheckedCount, cartCheckedChange }
    }, {
        persist: {
        enabled: true,
        strategies: [
        {
            key: 'cart',
            storage: localStorage
        }]
    }
})
export default useCart